//
//  ZJKRefreshControl.swift
//  MicroBlog
//
//  Created by VAD on 16/4/23.
//  Copyright © 2016年 朱江坤. All rights reserved.
//

import UIKit

enum ZJKRefreshControlState: Int {
    case Normal = 0//"默认"
    case Pulling = 1//"松手就去刷新的状态"
    case Refreshing = 2//"刷新中的状态"
}


// 刷新控件的高度
private let ZJKRefreshControlH: CGFloat = 50

class ZJKRefreshControl: UIControl {
    
    var zjkState: ZJKRefreshControlState = .Normal{
        didSet{
            switch zjkState{
            case .Pulling:
                // 1. 箭头朝上
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
                // 2. 更改文字为 "松手起飞"
                msgLabel.text = "松手起飞"
                
            case .Refreshing:
                // 1. 隐藏箭头
                self.arrowImage.hidden = true
                // 2. 菊花转
                self.indecatorView.startAnimating()
                // 3. 更改文字为 "正在起飞"
                msgLabel.text = "正在起飞"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 4. 将tableView的内容再往下移动 (多添加一部份滚动范围)
                    self.tableView?.contentInset.top =  self.tableView!.contentInset.top + ZJKRefreshControlH
                })
                
                // 去调用刷新的方法？？
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
            case .Normal:
                // 1. 隐藏菊花转
                self.indecatorView.stopAnimating()
                // 2. 显示箭头 朝下
                self.arrowImage.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowImage.transform = CGAffineTransformIdentity
                })
                // 3. 更改文字为 "等待起飞"
                msgLabel.text = "等待起飞"
                
                
                // 如果之前刷新中的状态，那么进入到Normal状态就减去顶部多出来的滑动距离
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25) { () -> Void in
                        self.tableView?.contentInset.top = self.tableView!.contentInset.top - ZJKRefreshControlH
                    }
                }

            }
        }
    }
    
    
    var tableView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){
        
        backgroundColor = UIColor.orangeColor()
        
        self.frame.size.height = ZJKRefreshControlH
        //将刷新控件添加到tableview的最上面
        self.frame.origin.y = -ZJKRefreshControlH
        
        // 1. 添加控件
        addSubview(arrowImage)
        addSubview(msgLabel)
        addSubview(indecatorView)
        
        
        // 2. 添加约束
        
        arrowImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        msgLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowImage)
            make.leading.equalTo(arrowImage.snp_trailing)
        }
        
        indecatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImage)
        }
        
    }
    
    func endRefresh(){
        
        zjkState = .Normal
        
        }
    
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        guard let tableView = newSuperview where tableView.isKindOfClass(UIScrollView.self) else{
            return
        }
        
        self.tableView = tableView as! UIScrollView
        
        self.frame.size.width = tableView.frame.width
        
        tableView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        let contentOffset = self.tableView!.contentOffset
        
        // 如何判断用户是否松手
        //        用户松手&当前状态是 "松手就去刷新"
        //-114
        let conditionValue = -tableView!.contentInset.top - ZJKRefreshControlH
        
        if tableView!.dragging{
            // 用户还在拖动
            if contentOffset.y < conditionValue && zjkState == .Normal {
                
                print("控件完全显示出来了")
                
                // 代表完全显示出来
                zjkState = .Pulling
                
            }else{
                
                if contentOffset.y >= conditionValue && zjkState == .Pulling {
                    
                    print("控件没有完全显示出来了")
                    
                    zjkState = .Normal
                }
            }
            
        }else{
            
            // 用户没有拖动 --> 松手，检查当前状态是否是pulling，如果是就进入到刷新状态
            if zjkState == .Pulling {
                
                print("控件进行刷新中")
                
                // 并且当前状态是松手就去刷新的话，就进行刷新中的状态
                zjkState = .Refreshing
            }
        }

    }
    
    deinit{
        tableView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    // MARK: - 懒加载控件
    
    // 箭头
    private lazy var arrowImage: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    // 提示label
    private lazy var msgLabel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 12)
        label.text = "等待起飞"
        return label
    }()
    
    // 菊花转
    private lazy var indecatorView: UIActivityIndicatorView = UIActivityIndicatorView()
    


}